﻿/// <reference path="jquery-1.7.1.min.js"/>

var cities;
var airlines;
var newspapers;
var units;

var newspapers_loaded = false;
var units_loaded = false;
var cities_loaded = false;
var airlines_loaded = false;

function loadCities() {
    $.ajax({
        type: "POST",
        url: "/new_order.aspx/GetCities",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            cities = msg.d;
            var city_select = '<option>---</option>';

            for (key in cities) {
                if (cities[key] == 'تهران')
                    city_select += '<option selected="selected">' + cities[key] + '</option>';
                else
                    city_select += '<option>' + cities[key] + '</option>';
            }

            $('#SourceCitySelect').html(city_select);
            $('#DestinationCitySelect').html(city_select);
            $('#DestinationCitySelect').val('---');
            cities_loaded = true;
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function loadNewspapers() {
    $.ajax({
        type: "POST",
        url: "/new_order.aspx/GetNewspapers",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            newspapers = msg.d;
            newspapers_loaded = true;
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function loadAirlines() {
    $.ajax({
        type: "POST",
        url: "/new_order.aspx/GetAirlines",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            airlines = msg.d;
            var airline_select = '<option>---</option>';
            for (key in airlines)
                airline_select += '<option>' + airlines[key] + '</option>';

            $('#AirlineSelect').html(airline_select);
            airlines_loaded = true;
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function loadUnits() {
    $.ajax({
        type: "POST",
        url: "/new_order.aspx/GetQuantityUnits",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            units = msg.d;
            units_loaded = true;
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function checkDataLoaded() {
    if (!newspapers_loaded || !units_loaded || !airlines_loaded || !cities_loaded) {
        $('#loading_progress').html('در حال بارگذاری اطلاعات، لطفا منتظر بمانید ...');
        $('#loading_progress').show();
        $('#order_content').hide();
        setTimeout(checkDataLoaded, 1000);
        return;
    }
    else {
        $('#order_content').show();
        $('#loading_progress').hide();
        $('#count').val('25');
        populateForm();
    }
}

function populateForm() {

    var count = parseInt($('#count').val());
    var orders_html = '';

    $('#orders').html('');

    for (i = 1; i <= count; i++) {
        orders_html += '<tr>';

        // newspapers
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'روزنامه';
        orders_html += '</td>';
        orders_html += '<td class="pad">';
        orders_html += '<select onchange="calculateUnitPrice(' + i + ')" id="Newspaper' + i + '">';
        orders_html += '<option>---</option>';
        for (key in newspapers)
            orders_html += '<option>' + newspapers[key] + '</option>';
        orders_html += '</td>';
        /**********************************************/

        // quantity
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'مقدار';
        orders_html += '</td>';
        orders_html += '<td><input type="text" onchange="calculateSum(' + i + ')" style="width:50px" id="Quantity' + i + '" /></td>';
        orders_html += '<td class="pad">';
        orders_html += '<select id="QuantityUnit' + i + '" tabindex="-1">';
        for (key in units)
            orders_html += '<option>' + units[key] + '</option>';
        orders_html += '</td>';
        /**********************************************/

        // Weight
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'وزن';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="text" onchange="calculateSum(' + i + ')" style="width:100px" id="Weight' + i + '" /></td>';
        /**********************************************/


        // unit price
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'قیمت واحد';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="text" style="width:80px"  onchange="calculateSum(' + i + ')" id="UnitPrice' + i + '" /></td>';
        /**********************************************/

        // packaging price
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'بسته بندی';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="text" style="width:80px"  onchange="calculateSum(' + i + ')" value="0" id="PackagingPrice' + i + '" /></td>';
        /**********************************************/

        // stamp price
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'تمبر';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="text" style="width:80px"  onchange="calculateSum(' + i + ')" value="0" id="StampPrice' + i + '" /></td>';
        /**********************************************/

        // tax
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'مالیات';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="text" onchange="calculateSum(' + i + ')" style="width:80px" id="Tax' + i + '" /></td>';
        /**********************************************/

        // minimum
        /**********************************************/
        orders_html += '<td>';
        orders_html += 'حداقل قیمت';
        orders_html += '</td>';
        orders_html += '<td class="pad"><input type="checkbox" id="MinAmount' + i + '" /></td>';
        /**********************************************/

        // messages
        /**********************************************/
        orders_html += '<td>';
        orders_html += '<span id="message' + i + '" class="message"></span>';
        orders_html += '</td>';
        /**********************************************/

        orders_html += '</tr>';
    }

    $('#orders').html(orders_html);
}

function reCalculateUnitPrice() {
    var count = parseInt($('#count').val());

    for (i = 1; i <= count; i++) {
        calculateUnitPrice(i);
    }
}

function calculateUnitPrice(i) {

    var source_city = $('#SourceCitySelect').val();
    var dest_city = $('#DestinationCitySelect').val();
    var airline_item = $('#AirlineSelect').val();
    var newspaper_item = $('#Newspaper' + i).val();


    $.ajax({
        type: "POST",
        url: "/new_order.aspx/GetUnitPrice",
        data: JSON.stringify({ sourceCity: source_city, destinationCity: dest_city, airline: airline_item, newspaper: newspaper_item }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            ReturnUnitPrice(msg.d, i);
        },
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

function ReturnUnitPrice(unitPrice, i) {
    $('#MessageTransfer').html("");
    $('#UnitPrice' + i).val("");

    if (unitPrice == "0") {
        $('#MessageTransfer').html("این مسیر پرواز تعریف نشده است");
    }
    else {
        $('#UnitPrice' + i).val(unitPrice);
    }

    calculateSum(i);
}

function calculateSum(i) {

    var q = $('#Quantity' + i).val();
    var w = $('#Weight' + i).val();
    var u = $('#UnitPrice' + i).val();
    var stamp = $('#StampPrice' + i).val();
    var packaging = $('#PackagingPrice' + i).val();

    if (w == NaN || u == NaN || w == '' || u == '') {
        $('#Tax' + i).val('0');
    }
    else {

        if (q * 17 > w) {
            alert('وزن  ' + q + ' ' + $('#QuantityUnit' + i).val() + ' روزنامه ' + $('#Newspaper' + i).val() + ' باید حداقل ' + q * 17 + ' کیلوگرم باشد آیا از صحیح بودن وزن اطمینان دارید؟ ');
        }

        if ((parseInt(q) + 1) * 17 < w) {
            alert('وزن  ' + q + ' ' + $('#QuantityUnit' + i).val() + ' روزنامه ' + $('#Newspaper' + i).val() + ' باید حداکثر ' + (parseInt(q) + 1) * 17 + ' کیلوگرم باشد آیا از صحیح بودن وزن اطمینان دارید؟ ');
        }

        var itemSum = parseInt(w * u) + parseInt(stamp) + parseInt(packaging);
        var tax = Math.round(itemSum * 0.04).toFixed();
        itemSum = parseInt(itemSum) + parseInt(tax);

        if ( itemSum.toString().length < 4 )
            itemSum = 1000;

        if (itemSum % 1000 != 0) 
            itemSum = itemSum + (1000 - (itemSum % 1000));

        if (itemSum < 70000 && this.confirm('مبلغ بارنامه از حداقل مجاز بارنامه کمتر شده است. آیا مایلید مبلغ حداقل جایگزین شود؟')) {
            itemSum = 70000;
            $('#MinAmount' + i).attr('checked', true);
        }
        else {
            $('#MinAmount' + i).attr('checked', false);
        }
        
        $('#message' + i).html(itemSum.toString() + ' ریال ');
        $('#Tax' + i).val(tax);
    }

    calculateTotalSum();
}

function calculateTotalSum() {
    var count = parseInt($('#count').val());
    var sum = 0;

    for (var i = 1; i < count; i++) {
        var q = $('#Weight' + i).val();
        var u = $('#UnitPrice' + i).val();
        var tax = parseFloat($('#Tax' + i).val());
        var stamp = $('#StampPrice' + i).val();
        var packaging = $('#PackagingPrice' + i).val();

        if (q == NaN || u == NaN || q == '' || u == '')
            ; // do nothing
        else {
            var item_sum = parseInt(q * u) + parseInt(tax) + parseInt(stamp) + parseInt(packaging);

            if (item_sum % 1000 != 0 )
                item_sum = item_sum + (1000 - (item_sum % 1000));

            if ($('#MinAmount' + i).is(':checked'))
                item_sum = 70000;
            
            sum = sum + item_sum;
        }
    }

    $('#total').html(sum);
}

function SubmitForm() {

    if ($('#count').val() == '---') {
        alert('لطفا اطلاعات بارنامه را وارد نمایید');
        return;
    }

    var count = parseInt($('#count').val());

    for (i = 1; i <= count; i++) {
        if ($('#MessageTransfer').html() == 'این مسیر پرواز تعریف نشده است') {
            alert('مسیر پرواز تعریف نشده است');
            return;
        }
    }

    $('#submit').hide();
    $('#result').show();

    var order_date = $('#OrderDate').val();
    var ajaxCalls = 0;
    var source_city = $('#SourceCitySelect').val();
    var dest_city = $('#DestinationCitySelect').val();
    var airline_item = $('#AirlineSelect').val();

    for (i = 1; i <= count; i++) {

        var newspaper_item = $('#Newspaper' + i).val();
        var unit_price = $('#UnitPrice' + i).val(); ;
        var quantity_value = $('#Quantity' + i).val();
        var quantity_unit = $('#QuantityUnit' + i).val();
        var tax_value = $('#Tax' + i).val(); ;
        var weight_value = $('#Weight' + i).val(); ;
        var min = $('#MinAmount' + i).is(':checked');
        var stamp = $('#StampPrice' + i).val();
        var packaging = $('#PackagingPrice' + i).val();

        $.ajax({
            type: "POST",
            url: "/new_order.aspx/AddOrder",
            data: JSON.stringify({ sourceCity: source_city, destinationCity: dest_city, airline: airline_item, newspaper: newspaper_item, unitPrice: unit_price, quantity: quantity_value, quantityUnit: quantity_unit, tax: tax_value, weight: weight_value, OrderDate: order_date, MinPrice: min, packagingPrice: packaging, stampPrice: stamp  }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                ajaxCalls++;
                if (ajaxCalls == count)
                    SaveOrders();
            },
            error: function (xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                $('#result').html(err.Message);
            }
        });
    }
}

function SaveOrders() {
    $.ajax({
        type: "POST",
        url: "/new_order.aspx/SaveOrders",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            ShowSubmitResults(msg.d);
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            $('#result').html(err.Message);
            $('#submit').show();
        }
    });
}

function ShowSubmitResults(orders) {

    var result = 'بارنامه ها با موفقیت ذخیره شدند.';
    $('#result').html(result);

    if ($('#SelectPrintDelay').val() == '-1') {
        PrintingFinished();
        return;
    }

    // sending the first print without any interval
    SendPrint(orders[0], 0, orders.length);

    if (orders.length == 1)
        return;

    // sending rest of prints with specified delay seconds intervals
    var i = 1;
    var delay = $('#SelectPrintDelay').val();

    var interval = setInterval(
                    function () {
                        SendPrint(orders[i], i, orders.length);
                        i++;
                        if (i >= orders.length)
                            clearInterval(interval);
                    }, parseInt(delay));
}

function SendPrint(orderId, i, length) {

    $('#result').html('ارسال بارنامه ' + (i + 1) + ' از ' + length + ' به چاپگر ' + ' ... ');

    $.ajax({
        type: "POST",
        url: "/new_order.aspx/PrintOrder",
        data: JSON.stringify({ OrderId: orderId }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            if (i == length - 1)
                PrintingFinished();
        },
        error: function (xhr, status, error) {
            // Boil the ASP.NET AJAX error down to JSON.
            var err = eval("(" + xhr.responseText + ")");
            $('#result').html(err.Message);
        }
    });
}

function PrintingFinished() {
    alert('تمام بارنامه ها با موفقیت ذخیره شدند');
    window.location = '/Orders/Insert.aspx';
}


